package health_system.health_system.controller;

import health_system.health_system.dto.FriendshipDTO;
import health_system.health_system.dto.PrivacySettingsDTO;
import health_system.health_system.dto.SimplePrivacySettingsDTO;
import health_system.health_system.dto.UserDTO;
import health_system.health_system.entity.PrivacySettings;
import health_system.health_system.exception.UserNotFoundException;
import health_system.health_system.repository.UserRepository;
import health_system.health_system.service.FriendshipService;
import health_system.health_system.service.SecurityService;
import health_system.health_system.service.UserService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.http.CacheControl;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Slf4j
@RestController
@RequestMapping("/api/friendships")
@RequiredArgsConstructor
public class FriendshipController {
    private final FriendshipService friendshipService;
    private final UserService userService;
    private final UserRepository userRepository;
    private final SecurityService securityService;
    /**
     * 创建好友关系（发送好友请求）
     */
    @PostMapping
    public ResponseEntity<FriendshipDTO> createFriendship(@Valid @RequestBody FriendshipDTO friendshipDTO) {

        log.debug("REST request to create friendship: {}", friendshipDTO);
        System.out.println(friendshipDTO);
        
        // 处理客户端特定的字段
        if (friendshipDTO.getRequestRemark() != null && friendshipDTO.getRequesterNote() == null) {
            // 如果requestRemark存在但requesterNote不存在，将requestRemark的值复制到requesterNote
            friendshipDTO.setRequesterNote(friendshipDTO.getRequestRemark());
        }
        
        // 创建默认的隐私设置（如果未提供）
        if (friendshipDTO.getPrivacySettings() == null) {
            PrivacySettingsDTO privacySettingsDTO = new PrivacySettingsDTO();
            privacySettingsDTO.setMoments(true);
            privacySettingsDTO.setLocation(true);
            privacySettingsDTO.setProfileInfo(true);
            privacySettingsDTO.setLastSeen(true);
            privacySettingsDTO.setPhone(false);
            privacySettingsDTO.setEmail(false);
            friendshipDTO.setPrivacySettings(privacySettingsDTO);
        }
        
        FriendshipDTO result = friendshipService.createFriendship(friendshipDTO);
        return ResponseEntity.ok(result);
    }

    /**
     * 创建好友关系（从客户端发送好友请求）
     * 处理客户端特定格式的请求
     */
    @PostMapping("/client")
    public ResponseEntity<FriendshipDTO> createFriendshipFromClient(@RequestBody Map<String, Object> requestData) {
        log.debug("REST request to create friendship from client: {}", requestData);
        
        try {
            // 提取必要信息
            Map<String, Object> requesterMap = (Map<String, Object>) requestData.get("requester");
            Map<String, Object> addresseeMap = (Map<String, Object>) requestData.get("addressee");
            String requesterNote = (String) requestData.get("requesterNote");
            Map<String, Object> privacySettingsMap = (Map<String, Object>) requestData.get("privacySettings");
            
            // 创建必要的DTO对象
            UserDTO requesterDTO = new UserDTO();
            if (requesterMap.containsKey("username")) {
                requesterDTO.setUsername((String) requesterMap.get("username"));
                // 通过用户名查找用户ID
                UserDTO foundUser = userService.getUserByUsername(requesterDTO.getUsername());
                requesterDTO.setId(foundUser.getId());
            } else if (requesterMap.containsKey("id")) {
                requesterDTO.setId(Long.valueOf(requesterMap.get("id").toString()));
            }
            
            UserDTO addresseeDTO = new UserDTO();
            if (addresseeMap.containsKey("id")) {
                addresseeDTO.setId(Long.valueOf(addresseeMap.get("id").toString()));
            }
            
            // 创建FriendshipDTO
            FriendshipDTO friendshipDTO = new FriendshipDTO();
            friendshipDTO.setRequester(requesterDTO);
            friendshipDTO.setAddressee(addresseeDTO);
            friendshipDTO.setRequesterNote(requesterNote);
            
            // 处理隐私设置
            if (privacySettingsMap != null) {
                PrivacySettingsDTO privacySettingsDTO = new PrivacySettingsDTO();
                privacySettingsDTO.setMoments(Boolean.TRUE.equals(privacySettingsMap.get("moments")));
                privacySettingsDTO.setLocation(Boolean.TRUE.equals(privacySettingsMap.get("location")));
                // 设置默认值
                privacySettingsDTO.setProfileInfo(true);
                privacySettingsDTO.setLastSeen(true);
                privacySettingsDTO.setPhone(false);
                privacySettingsDTO.setEmail(false);
                
                friendshipDTO.setPrivacySettings(privacySettingsDTO);
            }
            
            // 创建好友关系
            FriendshipDTO result = friendshipService.createFriendship(friendshipDTO);
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("Error creating friendship from client request: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 接收移动客户端发送的好友请求
     * 处理特定格式的请求，支持通过username查找用户
     */
    @PostMapping("/mobile")
    public ResponseEntity<FriendshipDTO> createFriendshipFromMobile(@RequestBody Map<String, Object> requestData) {
        log.debug("REST request to create friendship from mobile client: {}", requestData);
        System.out.println(requestData);
        
        try {
            // 提取必要信息
            Map<String, Object> requesterMap = (Map<String, Object>) requestData.get("requester");
            Map<String, Object> addresseeMap = (Map<String, Object>) requestData.get("addressee");
            String requesterNote = (String) requestData.get("requesterNote");
            String requestRemark = (String) requestData.get("requestRemark");
            Map<String, Object> privacySettingsMap = (Map<String, Object>) requestData.get("privacySettings");
            
            // 如果requesterNote为空但requestRemark不为空，使用requestRemark
            if ((requesterNote == null || requesterNote.isEmpty()) && requestRemark != null && !requestRemark.isEmpty()) {
                requesterNote = requestRemark;
            }
            
            // 创建必要的DTO对象
            UserDTO requesterDTO = new UserDTO();
            // 处理requester信息
            if (requesterMap != null) {
                if (requesterMap.containsKey("username")) {
                    String username = (String) requesterMap.get("username");
                    requesterDTO.setUsername(username);
                    try {
                        // 通过用户名查找用户ID
                        UserDTO foundUser = userService.getUserByUsername(username);
                        requesterDTO.setId(foundUser.getId());
                        log.debug("Found requester user by username {}: ID={}", username, foundUser.getId());
                    } catch (UserNotFoundException e) {
                        log.error("Requester username not found: {}", username);
                        return ResponseEntity.badRequest().body(null);
                    }
                } else if (requesterMap.containsKey("id")) {
                    requesterDTO.setId(Long.valueOf(requesterMap.get("id").toString()));
                }
            } else {
                // 如果没有提供requester信息，尝试使用当前登录用户
                Long currentUserId = securityService.getCurrentUserId();
                if (currentUserId != null) {
                    requesterDTO.setId(currentUserId);
                } else {
                    log.error("No requester information provided and no authenticated user");
                    return ResponseEntity.badRequest().body(null);
                }
            }
            
            // 确保requester有ID
            if (requesterDTO.getId() == null) {
                log.error("Could not determine requester ID");
                return ResponseEntity.badRequest().body(null);
            }
            
            // 处理addressee信息
            UserDTO addresseeDTO = new UserDTO();
            if (addresseeMap != null) {
                if (addresseeMap.containsKey("id")) {
                    addresseeDTO.setId(Long.valueOf(addresseeMap.get("id").toString()));
                } else if (addresseeMap.containsKey("username")) {
                    String username = (String) addresseeMap.get("username");
                    try {
                        // 通过用户名查找用户ID
                        UserDTO foundUser = userService.getUserByUsername(username);
                        addresseeDTO.setId(foundUser.getId());
                        log.debug("Found addressee user by username {}: ID={}", username, foundUser.getId());
                    } catch (UserNotFoundException e) {
                        log.error("Addressee username not found: {}", username);
                        return ResponseEntity.badRequest().body(null);
                    }
                }
            }
            
            // 确保addressee有ID
            if (addresseeDTO.getId() == null) {
                log.error("Could not determine addressee ID");
                return ResponseEntity.badRequest().body(null);
            }
            
            // 创建FriendshipDTO
            FriendshipDTO friendshipDTO = new FriendshipDTO();
            friendshipDTO.setRequester(requesterDTO);
            friendshipDTO.setAddressee(addresseeDTO);
            friendshipDTO.setRequesterNote(requesterNote);
            
            // 处理隐私设置
            PrivacySettingsDTO privacySettingsDTO = new PrivacySettingsDTO();
            if (privacySettingsMap != null) {
                privacySettingsDTO.setMoments(Boolean.TRUE.equals(privacySettingsMap.get("moments")));
                privacySettingsDTO.setLocation(Boolean.TRUE.equals(privacySettingsMap.get("location")));
                privacySettingsDTO.setProfileInfo(Boolean.TRUE.equals(privacySettingsMap.get("profileInfo")));
                privacySettingsDTO.setLastSeen(Boolean.TRUE.equals(privacySettingsMap.get("lastSeen")));
                privacySettingsDTO.setPhone(Boolean.TRUE.equals(privacySettingsMap.get("phone")));
                privacySettingsDTO.setEmail(Boolean.TRUE.equals(privacySettingsMap.get("email")));
            } else {
                // 设置默认值
                privacySettingsDTO.setMoments(true);
                privacySettingsDTO.setLocation(true);
                privacySettingsDTO.setProfileInfo(true);
                privacySettingsDTO.setLastSeen(true);
                privacySettingsDTO.setPhone(false);
                privacySettingsDTO.setEmail(false);
            }
            
            friendshipDTO.setPrivacySettings(privacySettingsDTO);
            
            log.debug("Prepared friendship DTO for creation: {}", friendshipDTO);
            FriendshipDTO result = friendshipService.createFriendship(friendshipDTO);
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("Error creating friendship from mobile client request: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 获取用户的好友列表
     */
    @GetMapping("/friends/{userId}")
    public ResponseEntity<List<UserDTO>> getFriendsByUser(@PathVariable Long userId) {
        log.debug("REST request to get friends for user: {}", userId);
        
        try {
            List<UserDTO> friends = friendshipService.getFriendsByUser(userId);
            log.debug("Found {} friends for user {}: {}", friends.size(), userId, friends);
            return ResponseEntity
                .ok()
                .cacheControl(CacheControl.noCache().noStore().mustRevalidate())
                .header("Pragma", "no-cache")
                .header("Expires", "0")
                .body(friends);
        } catch (Exception e) {
            log.error("Error retrieving friends for user {}: {}", userId, e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 获取用户的待处理好友请求
     */
    @GetMapping("/pending/{userId}")
    public ResponseEntity<List<FriendshipDTO>> getPendingFriendRequests(@PathVariable Long userId) {
        log.debug("REST request to get pending friend requests for user: {}", userId);
        List<FriendshipDTO> pendingRequests = friendshipService.getPendingFriendRequests(userId);
        
        // Add cache control headers
        return ResponseEntity
            .ok()
            .cacheControl(CacheControl.noCache().noStore().mustRevalidate())
            .header("Pragma", "no-cache")
            .header("Expires", "0")
            .body(pendingRequests);
    }
    
    /**
     * 获取当前用户的待处理好友请求
     */
    @GetMapping("/pending/current")
    public ResponseEntity<List<FriendshipDTO>> getCurrentUserPendingRequests() {
        Long currentUserId = securityService.getCurrentUserId();
        
        if (currentUserId == null) {
            log.error("Failed to get current user id from security context");
            return ResponseEntity.badRequest().build();
        }
        
        log.debug("REST request to get pending friend requests for current user: {}", currentUserId);
        List<FriendshipDTO> pendingRequests = friendshipService.getPendingFriendRequests(currentUserId);
        
        log.info("Found {} pending friend requests for user {}", pendingRequests.size(), currentUserId);
        
        // Add cache control headers
        return ResponseEntity
            .ok()
            .cacheControl(CacheControl.noCache().noStore().mustRevalidate())
            .header("Pragma", "no-cache")
            .header("Expires", "0")
            .body(pendingRequests);
    }

    /**
     * 接受好友请求
     */
    @PostMapping("/{id}/accept")
    public ResponseEntity<FriendshipDTO> acceptFriendship(@PathVariable Long id) {
        log.debug("REST request to accept friendship: {}", id);
        FriendshipDTO result = friendshipService.acceptFriendship(id);
        return ResponseEntity.ok(result);
    }

    /**
     * 拒绝好友请求
     */
    @PostMapping("/{id}/reject")
    public ResponseEntity<FriendshipDTO> rejectFriendship(@PathVariable Long id) {
        log.debug("REST request to reject friendship: {}", id);
        FriendshipDTO result = friendshipService.rejectFriendship(id);
        return ResponseEntity.ok(result);
    }

    /**
     * 删除好友关系
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteFriendship(@PathVariable Long id) {
        log.debug("REST request to delete friendship: {}", id);
        friendshipService.deleteFriendship(id);
        return ResponseEntity.noContent().build();
    }

    /**
     * 通过手机号或邮箱搜索用户
     */
    @GetMapping("/search")
    public ResponseEntity<List<UserDTO>> searchUsers(
            @RequestParam(required = false) String phoneNumber,
            @RequestParam(required = false) String email) {
        
        log.debug("REST request to search users by phone number: {} or email: {}", phoneNumber, email);
        
        List<UserDTO> users = new ArrayList<>();
        
        if (phoneNumber != null && !phoneNumber.isEmpty()) {
            try {
                UserDTO user = userService.getUserByPhoneNumber(phoneNumber);
                users.add(user);
            } catch (UserNotFoundException e) {
                log.debug("User not found with phone number: {}", phoneNumber);
            }
        } else if (email != null && !email.isEmpty()) {
            try {
                UserDTO user = userService.getUserByEmail(email);
                users.add(user);
            } catch (UserNotFoundException e) {
                log.debug("User not found with email: {}", email);
            }
        }
        
        return ResponseEntity.ok(users);
    }

    /**
     * 查询两个用户之间的好友关系
     */
    @GetMapping("/between")
    public ResponseEntity<FriendshipDTO> getFriendshipBetweenUsers(
            @RequestParam Long userId1,
            @RequestParam Long userId2) {
        
        log.debug("REST request to find friendship between users: {} and {}", userId1, userId2);
        
        Optional<FriendshipDTO> friendship = friendshipService.findFriendshipBetweenUsers(userId1, userId2);
        
        return friendship
                .map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }
} 